﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using JinianNet.JNCms.Models;

namespace JinianNet.JNCms.Controllers
{
    public class AttachmentController : ControllerBase
    {
        [HttpPost]
        public ActionResult UpLoad(bool MakeThumbnails)
        {
            //HttpFileCollectionBase files = Request.Files;
            List<Attachment> list = new List<Attachment>();

            JinianNet.JNCms.Data.IAttachment dal = JinianNet.JNCms.Data.DataAccess.CreateAttachment();

            for (var i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase f = Request.Files[i];
                Attachment model = new Attachment();
                model.CreateTime = DateTime.Now;
                model.Extension = System.IO.Path.GetExtension(f.FileName);
                model.Folder = DateTime.Now.ToString("yyyy/MM/dd");
                model.Mime = f.ContentType;
                model.OriginalName = System.IO.Path.GetFileName(f.FileName);
                model.SaveName = JinianNet.Common.Random.RandTime(10);
                model.Size = f.ContentLength;
                model.Title = model.OriginalName;
                model.TypeID = 0;
                model.ValueID = 0;
                model.IsPicture = model.Extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || model.Extension.Equals(".png", StringComparison.OrdinalIgnoreCase) || model.Extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase) || model.Extension.Equals(".gif", StringComparison.OrdinalIgnoreCase) || model.Extension.Equals(".bmp", StringComparison.OrdinalIgnoreCase);

                string path = Server.MapPath(JinianNet.Common.Url.Concat("~", Config.Site.SiteDirectory, "Resources/UploadFles", model.Folder));
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                if (path.EndsWith("\\"))
                    path = path.TrimEnd('\\');
                f.SaveAs(string.Concat(path, "\\", model.SaveName, model.Extension));

                if (model.IsPicture && MakeThumbnails)
                {
                    model.HasThumbnails = true;
                    model.ThumbnailName = string.Concat(model.SaveName, "_Thumb");
                    MakeThumbnail(string.Concat(path, "\\", model.SaveName, model.Extension), string.Concat(path, "\\", model.ThumbnailName, model.Extension),int.Parse( Config.Site.PhotoThumbWidth), int.Parse(Config.Site.PhotoThumbHeight));
                }
                else
                {
                    model.HasThumbnails = false;
                    model.ThumbnailName = string.Empty;
                }
          
                dal.Insert(model);
                list.Add(model);
            }

            return View("Insert",(object)list);
        }

        public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (ow > oh)
            {
                toheight = originalImage.Height * width / originalImage.Width;
            }
            else
            {
                towidth = originalImage.Width * height / originalImage.Height;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        public ActionResult Insert()
        {
            return View();
        }

        public ActionResult List(int page = 1, int size = 0)
        {
            if (size <= 0)
                size = Config.Page.Size;
            var list = Data.DataAccess.CreateAttachment().GetList(page, size);

            string home, pre, next;
            if (page > 1)
            {
                home = Url.Action("List", "Attachment");
                pre = Url.Action("List", "Attachment", new { page = page - 1 });

            }
            else
            {
                home = null;
                pre = null;
            }
            if (list.Count == size)
            {
                next = Url.Action("List", "Attachment", new { page = page + 1 });
            }
            else
            {
                ;
                next = null;
            }
            ViewData["WebPage"] = JinianNet.Web.PageLinker.GetActionLinker(home, pre, next);
            return View(list);
        }


        public ActionResult Delete(string item)
        {
            Data.IAttachment dal = Data.DataAccess.CreateAttachment();
            string[] list;
            if (item.IndexOf(',') < 0)
                list = new string[] { item };
            else
                list = item.Split(',');
            foreach (string value in list)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    int id = int.Parse(value);
                    Models.Attachment model = dal.GetItem(id);
                    if (model != null)
                    {
                        string path = Server.MapPath(JinianNet.Common.Url.Concat("~", Config.Site.SiteDirectory, "Resources/UploadFles", model.Folder, string.Concat(model.SaveName, model.Extension)));
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                        dal.Delete(id);
                    }
                }
            }
            return Content(Config.GetTips("操作成功", null, true));
        }
    }
}
